package com.dmlll.servlet;

import com.dmlll.dao.UserDao;
import com.dmlll.demo.User;
import com.dmlll.service.UserService;
import com.dmlll.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username != null && password != null){
            //查询username
            List<User> list = userService.findByUserName(username);
            for (User user: list){
                if(username.equals(user.getUsername()) && password.equals(user.getPassword()) ){
                    //保存登录信息
                    HttpSession session = req.getSession();
                    session.setAttribute("username",username);
                    //登录成功，跳转到登录
                    req.getRequestDispatcher("/page/success.jsp").forward(req,resp);
                    return;
                }
            }
            req.getRequestDispatcher("/page/fail.jsp").forward(req,resp);
        }
    }
}
